package com.cyx.controller;

import com.cyx.anno.LogOperation;
import com.cyx.pojo.Dept;
import com.cyx.pojo.Result;
import com.cyx.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RequestMapping("/depts")
@RestController
public class DeptController {

    @Autowired
    private DeptService deptService;

    // method是用来指定请求方式的
    // @RequestMapping(value = "/depts",method = RequestMethod.GET)
    @GetMapping
    public Result list(){
        log.info("查询全部的部门数据");
        List<Dept> deptList = deptService.findAll();
        return Result.success(deptList);
    }
    /**
     * 删除部门信息
     * 注意事项：
     * 一旦声明了@RequestParam 的参数，那么这个参数必须通过这个参数名来获取参数值
     * 否则，SpringMVC无法获取参数值 会报错 默认的 required = true
     *
     */
//    @DeleteMapping("/depts")
//    public Result delete(@RequestParam(value = "id",required = false) Integer deptId){
//        System.out.println("根据ID删除部门" + deptId);
//        return Result.success();
//    }
    // 保证前端请求的参数名和服务端的参数名一致
    @LogOperation
    @DeleteMapping
    public Result delete(Integer id){
        log.info("根据ID删除部门: {}" ,id);
        deptService.deleteById(id);
        return Result.success();
    }



//    @DeleteMapping("/depts")
//    public Result delete(HttpServletRequest request){
//        String idStr = request.getParameter("id");
//        int id = Integer.parseInt(idStr);
//        System.out.println("根据ID删除部门" + id);
//        return Result.success();
//    }

    /**
     * 新增部门
     */
    @LogOperation
    @PostMapping
    public Result add(@RequestBody Dept dept){
        log.info("新增部门: {}",dept);
        deptService.add(dept);
        return Result.success();
    }

    /**
     * 根据id查询部门信息
     *
     */
    @GetMapping("/{id}")
    public Result getInfo(@PathVariable Integer id){
        log.info("根据ID查询部门信息: {}",id);
        Dept dept = deptService.getById(id);
        return Result.success(dept);
    }

    /**
     *
     * 修改部门信息
     */
    @LogOperation
    @PutMapping
    public Result update(@RequestBody Dept dept){
        System.out.println("修改部门:" + dept);
        deptService.update(dept);
        return Result.success();
    }
}
